package com.eolcum.evo.service;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import com.eolcum.evo.persistence.DataBaseHelper;
import com.eolcum.evo.persistence.Sensor;
import com.google.gson.Gson;

import android.app.Service;
import android.content.Intent;
import android.database.SQLException;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class EvoAPIService  extends Service  {

	private static final String TAG = "EvoAPIService";
	private DataBaseHelper db;
	
	@Override
	public void onCreate() {
		
		db = new DataBaseHelper(getApplicationContext());

		try {
			db.createDataBase();
		} catch (IOException ioe) {
			throw new Error("Unable to create database");
		}

		try {
			db.openDataBase();
		} catch (SQLException sqle) {
			throw sqle;
		}
		Log.d(TAG, "Service created.");
		super.onCreate();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "Service started.");
		
		if ("getSensorHistory".equals(intent.getExtras().getString("function_name"))) {
			Gson gson = new Gson();
			String id = intent.getExtras().getString("id");
			String serialNo = intent.getExtras().getString("serialNo");
			long minTimeStamp = intent.getExtras().getLong("minTimeStamp", 0L);
			long maxTimeStamp = intent.getExtras().getLong("maxTimeStamp", Calendar.getInstance().getTimeInMillis());
			List<Sensor> sensorHistory = db.getSensorHistory(id, serialNo, minTimeStamp, maxTimeStamp);
			Log.i("sensorLogId", "" + gson.toJson(sensorHistory));
		}		
		
		return super.onStartCommand(intent, flags, startId);
	}
	
	IBinder mBinder = new EvoAPIServiceLocalBinder();

	@Override
	public IBinder onBind(Intent intent) {

		return mBinder;
	}

	public class EvoAPIServiceLocalBinder extends Binder {
		public EvoAPIService getServerInstance() {
			return EvoAPIService.this;
		}
	}

}
